/*
 * Copyright 2009 XueSong Guo.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.webwheel;

import java.util.*;

class FilterGroupImpl implements FilterGroup {

    Filter[] filters;

    private Map<String, Class<? extends Action>> actions = new HashMap<String, Class<? extends Action>>();

    private Main main;

    private FilterGroup parent;
    private List<FilterGroupImpl> children = new ArrayList<FilterGroupImpl>();

    FilterGroupImpl(Main main) {
        this.main = main;
        filters = new Filter[0];
    }

    public FilterGroupImpl append(Filter filter) {
        if (filter == null) {
            throw new IllegalArgumentException("filter is null");
        }
        for (FilterGroupImpl child : children) {
            if (child.filters[filters.length] == filter) {
                return child;
            }
        }
        FilterGroupImpl nfg = new FilterGroupImpl(main);
        nfg.parent = this;
        nfg.filters = new Filter[filters.length + 1];
        System.arraycopy(filters, 0, nfg.filters, 0, filters.length);
        nfg.filters[filters.length] = filter;
        children.add(nfg);
        return nfg;
    }

    public void bindAction(String path, Class<? extends Action> actionClass) {
        main.bindAction(path, actionClass, this);
        actions.put(path, actionClass);
    }

    public List<Filter> getFilters() {
        return Collections.unmodifiableList(Arrays.asList(filters));
    }

    public Map<String, Class<? extends Action>> getActions() {
        Map<String, Class<? extends Action>> map = new HashMap<String, Class<? extends Action>>(actions);
        for (FilterGroup child : children) {
            map.putAll(child.getActions());
        }
        return map;
    }

    public FilterGroup getParent() {
        return parent;
    }

    public List<? extends FilterGroup> getChildren() {
        return Collections.unmodifiableList(children);
    }
}
